import React, { useEffect, useRef, useState } from 'react';
import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Space,
  Upload,
} from 'antd';
import { Link } from 'react-router-dom';
import Channel from './../../components/Channel';
/*
  学习目标：使用富文本组件react-quill
*/
// 1.下包
// 2. 导入组件和样式
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

import styles from './index.module.scss';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';

import { UploadOutlined } from '@ant-design/icons';
import {
  getArticleByIdAPI,
  publishArticleAPI,
  updateArticleAPI,
} from './../../api/article';
/*
  学习目标：处理富文本校验
  
*/
export default function ArticlePublish(myProps) {
  // 1. 声明type的state
  const [type, setType] = useState(1);

  // 0. 接口提前改造
  // 1. 声明ref，保存draft的标识
  const draftRef = useRef(false);
  const formRef = useRef({});
  // 3. 事件冒泡到onFinish时，请求参数中带上ref

  const [fileList, setFileList] = useState([]);
  const [imgSrc, setImgSrc] = useState('');
  const props = {
    name: 'image',
    accept: '.png,.jpg,.jpeg',
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      console.log('info ------ ', info);
      setFileList(info.fileList);
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`, 1);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败.`, 1);
      }
    },
    onPreview(file) {
      console.log('file', file);
      // 4. 回填预览图片地址
      setImgSrc(file.thumbUrl || file.url);
    },
    beforeUpload(file) {
      const imgs = ['image/jpg', 'image/png', 'image/jpeg'];

      if (!imgs.includes(file.type)) {
        message.warning('不允许上传的文件类型', 1);
        return Upload.LIST_IGNORE;
      }
    },
  };

  const showFileList = fileList.filter((item, index) => {
    if (type === 0) return false;
    if (type === 1) return index === 0;
    return true;
  });

  // 2. 绑定onValuesChange事件，任意值改变事件
  const handleValuesChange = (changedValues, allValue) => {
    // 2.1 判断changedValues有type这个属性，且不为undefined的时候，setState更新type
    if (changedValues.type !== undefined) {
      setType(changedValues.type);
    }
  };

  const handleFinish = async (values) => {
    // 1. 加判断条件 -数量不对,提示用户阻止执行
    if (showFileList.length !== type) {
      return message.warning('图片数量不正确', 1);
    }
    // 1. 按接口要求，拼装formData
    let formData = {
      ...values,
    };

    formData.cover = {
      // 2.转换type和images
      type: values.type,
      // 💥images是url字符串组成的数组
      // 2. 以用户界面上看到的为准，发给后台
      images: showFileList.map((item) =>
        item.response ? item.response.data.url : item.url
      ),
    };

    // 3. 删除没有的值
    delete formData.type;

    if (articleId) {
      await updateArticleAPI(articleId, formData, draftRef.current);
      message.success('编辑成功', 1);
    } else {
      await publishArticleAPI(formData, draftRef.current);
      message.success('发表成功', 1);
    }

    myProps.history.push('/list');

    console.log('formData  ----->  ', formData);
  };
  console.log('myProps', myProps);
  // 3. 获取传来id
  const articleId = myProps.match.params.id;
  const loadArticleById = async (id) => {
    const res = await getArticleByIdAPI(id);
    console.log('res---', res);
    console.log('res.data---', res.data);
    formRef.current.setFieldsValue({ ...res.data, type: res.data.cover.type });
    setType(res.data.cover.type);
    setFileList(res.data.cover.images.map((item) => ({ url: item })));
  };

  useEffect(() => {
    if (articleId) {
      loadArticleById(articleId);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  return (
    // 3.调整样式
    <div
      style={{
        height: 'calc( 100vh - 64px )',
        overflow: 'auto',
        padding: '24px',
      }}
      className={styles.publish}
    >
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to={'/home'}>首页 </Link>{' '}
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              {`${articleId ? '编辑' : '发布'}`}文章
            </Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          name="basic"
          size="large"
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          autoComplete="off"
          onFinish={handleFinish}
          initialValues={{
            content: '',
            type: 1,
          }}
          onValuesChange={handleValuesChange}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入文章标题' }]}
          >
            <Input placeholder="请输入文章标题" />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择频道' }]}
          >
            <Channel allowClear></Channel>
          </Form.Item>
          <Form.Item
            label="内容"
            name="content"
            rules={[
              // 3. 加上星号

              {
                message: '文章内容不能为空',
                validator: (_, value) => {
                  // 判断value的值为   返回失败的信息
                  // 1. 判断是否为空标签
                  // 2.使用自定义校验，返回  Promise.resolve() 代表通过。 Promise.reject()代表失败
                  if (value === '<p><br></p>') {
                    return Promise.reject(new Error('内容不能为空'));
                  }
                  return Promise.resolve();
                },
              },
              {
                required: true,
                message: '内容不能为空',
              },
            ]}
          >
            <ReactQuill theme="snow"></ReactQuill>
          </Form.Item>
          <Form.Item label="封面" name="type">
            <Radio.Group>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Upload {...props} listType="picture-card" fileList={showFileList}>
              {/* 4. 使用表达式控制按钮的显示与否 */}
              {fileList.length < type ? <UploadOutlined /> : null}
            </Upload>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {`${articleId ? '编辑' : '发布'}`}文章
              </Button>
              {/*   2. Button点击时，改变ref存储draft的值为true 🔑 htmlType设置为submit */}
              <Button
                type="primary"
                htmlType="submit"
                onClick={() => (draftRef.current = true)}
              >
                存草稿
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        maskClosable={false}
        title="预览图片"
        visible={!!imgSrc}
        footer={null}
        onCancel={() => setImgSrc('')}
      >
        <img width={480} style={{ objectFit: 'cover' }} src={imgSrc} alt="" />
      </Modal>
    </div>
  );
}
